package chapter5_基础构建模块.同步工具类;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class FutureTaskTest {
    private final FutureTask<Integer> future = new FutureTask<Integer>(new Callable<Integer>() {
        @Override
        public Integer call() throws Exception {
            //do some figure
            return 100;
        }
    });
    private final Thread thread = new Thread(future);

    public void start() {
        thread.start();
    }

    public Integer get() throws InterruptedException {
        try {
            return future.get();
        } catch (ExecutionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof BizException) {
                throw (BizException) cause;
            } else {
                throw launderThrowable(cause);
            }
        }
    }

    public static RuntimeException launderThrowable(Throwable t) {
        if (t instanceof RuntimeException) {
            return (RuntimeException) t;
        } else if (t instanceof Error) {
            throw  (Error) t;
        } else {
            throw new IllegalStateException("Not unchecked", t);
        }
    }
}

// 自定义业务异常
class BizException extends RuntimeException {

}
